package class8;

import common.TreeNode;
import common.TreeNodeUtils;

import java.lang.reflect.Array;
import java.util.*;

/**
 * 求二叉树的最大宽度
 */
public class Code06_BinaryTreeWidth {

    public static void main(String[] args) {
        TreeNode treeNode = TreeNodeUtils.getTreeNode();
        List<List<Integer>> lists = levelIter(treeNode);
        System.out.println("lists = " + lists);
        //
        int maxWidth = maxWidth(treeNode);
        System.out.println("maxWidth = " + maxWidth);
    }

    public static List<List<Integer>> levelIter(TreeNode treeNode) {
        if (treeNode == null) return null;
        int max = 0;
        List<List<Integer>> ans = new ArrayList();
        Queue<TreeNode> queue = new LinkedList();
        queue.add(treeNode);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                list.add(poll.val);
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
            ans.add(list);
        }
        return ans;
    }

    public static int maxWidth(TreeNode treeNode) {
        if (treeNode == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(treeNode);
        int max = 0;

        Map<TreeNode, Integer> levelMap = new HashMap<TreeNode, Integer>() {{
            put(treeNode, 1);
        }};
        int curLevel = 1; // 当前正在统计那一层的宽度
        int curNodeNums = 0; // 当前层的宽度是多少

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            int curNodeLevel = levelMap.get(cur); // 当前节点在哪一层
            if (cur.left != null) {
                levelMap.put(cur.left, curNodeLevel + 1); // 记录在哪层
                queue.add(cur.left);
            }
            if (cur.right != null) {
                levelMap.put(cur.right, curNodeLevel + 1); // 记录在哪层
                queue.add(cur.right);
            }
            if (curLevel == curNodeLevel) {
                curNodeNums++;
            } else {
                max = Math.max(max, curNodeNums);
                curLevel++;
                curNodeNums = 1;
            }
        }
        max = Math.max(max, curNodeNums);
        return max;

    }
}
